#ifndef SENSOR_C
#define SENSOR_C
#include "sensor.h"

static pthread_t pid;

static int fp=0;
static float temper_value,humi_value;

typedef union{
	unsigned int i;
	float f;
}value;


static void calc_sth11(float *p_humidity ,float *p_temperature)
{
	float C1=-4.0;				// for 12 Bit	
	float C2=+0.0405;			// for 12 Bit	
	float C3=-0.0000028;		// for 12 Bit	
	float T1=+0.01; 			// for 14 Bit @ 5V	 
	float T2=+0.00008; 		  // for 14 Bit @ 5V  
	float rh=*p_humidity; 			// rh:		Humidity [Ticks] 12 Bit  
	float t=*p_temperature;		   // t:	   Temperature [Ticks] 14 Bit  
	float rh_lin;					 // rh_lin:  Humidity linear  
	float rh_true;					// rh_true: Temperature compensated humidity  
	float t_C;						// t_C	 :	Temperature  t_C=t*0.01 - 40;				   //calc. temperature from ticks  
	rh_lin=C3*rh*rh + C2*rh + C1;	 //calc. humidity from ticks to [%RH]  
	rh_true=(t_C-25)*(T1+T2*rh)+rh_lin;	 //calc. temperature compensated humidity [%RH]  
	if(rh_true>100)rh_true=100;	   //cut if the value is outside of  
	if(rh_true<0.1)rh_true=0.1;	   //the physical possible range  
	*p_temperature=t_C;				//return temperature  
	*p_humidity=rh_true;				//return humidity[%RH]
}

static void GetSht(value *temp,value *humi,unsigned char *tt)
{    
	temp->i=tt[0];    
	temp->i=(temp->i)<<8;    
	temp->i+=tt[1];    
	humi->i=tt[2];    
	humi->i=(humi->i)<<8;    
	humi->i+=tt[3];    
	temp->f=(float)temp->i;    
	humi->f=(float)humi->i;    
	calc_sth11(&(humi->f),&(temp->f));
}

static void Sensor_thread()
{
	value temp,humi;
	unsigned char t[4];
	while(1){
		read(fp,t,0);			  
		GetSht(&temp,&humi,t);			
		temper_value=temp.f;			
		humi_value=humi.f;
		msleep(SENSOR_INTERVAL);
	}
}

RETURN_ID Drv_Sensor_Init()
{
	int err;
	fp=open("/dev/HW_SHT",0);
	if(fp<0)
		return -SENSOR_OPEN_FAILED;
	if(!fp)
		return -SENSOR_NOT_OPEN;
	err=pthread_create(&pid,NULL,(void *)Sensor_thread,NULL);
	if(err!=0){
		DBGINFO("can't create sensor_thread %s\n!!",strerror(err));
		return -SENSOR_CREATETHREAD_FAILED;
	}
	return -NO_ERROR;
}

RETURN_ID Drv_Sensor_UnInit()
{
	pthread_cancel(pid);
	if(fp)
		close(fp);
	fp=0;
	return -NO_ERROR;
}

float Drv_Get_Temper()
{
	return temper_value;
}

float Drv_Get_Humi()
{
	return humi_value;
}

#endif
